import shell from 'shelljs'
import chalk from 'chalk'
import { readFile } from 'node:fs/promises'

// 在哪个目录下执行的，就读取对应目录的 package.json
const { name, version } = JSON.parse(await readFile('./package.json'))

const title = chalk.black(`[version check]`)

console.log(title, chalk.black(`${name}@${version}`))

// 如果是私有 npm 源，修改 registry 的链接
const { code, stdout } = shell.exec(`npm view ${name} versions --registry=https://registry.npm.taobao.org`, {
  silent: true
})

if (code === 0) {
  const versions = stdout.replace(/(\[|\]|\s+|\'|\")/g, '').split(',')

  if (versions.includes(version)) {
    console.log(title, chalk.red(`${name}@${version} 已存在，请更改版本号后再进行打包！\n`))
    process.exit(1)
  }
}

console.log(title, chalk.green('check pass!'))
